package com.sh.data.engine.application.service.api;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.google.common.collect.Lists;
import com.sh.data.engine.application.model.dto.api.DataApiBaseResponse;
import com.sh.data.engine.application.model.dto.api.DataApiLogResponse;
import com.sh.data.engine.application.model.dto.api.DataApiResponse;
import com.sh.data.engine.application.model.dto.common.DirectoryResponse;
import com.sh.data.engine.common.exception.BusinessException;
import com.sh.data.engine.common.util.ServletUtils;
import com.sh.data.engine.domain.api.model.domain.DataApiDomain;
import com.sh.data.engine.domain.api.model.domain.DataApiLogDomain;
import com.sh.data.engine.domain.api.model.domain.DataApiRegisterDomain;
import com.sh.data.engine.domain.api.model.domain.rest.DataApiBaseDomain;
import com.sh.data.engine.domain.api.model.domain.rest.DataApiTaskParamDomain;
import com.sh.data.engine.domain.api.service.DataApiAuthService;
import com.sh.data.engine.domain.api.service.DataApiService;
import com.sh.data.engine.domain.base.model.PageResult;
import com.sh.data.engine.domain.base.model.UserContext;
import com.sh.data.engine.domain.base.model.enums.DirectoryMenuEnum;
import com.sh.data.engine.domain.common.model.domain.DirectoryDomain;
import com.sh.data.engine.domain.common.service.DirectoryService;
import com.sh.data.engine.domain.util.ConvertUtil;
import com.sh.data.engine.domain.workspace.manager.model.domain.UserDomain;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author: mengzheng.mhc
 * @date: 2024/8/15 17:05
 */
@Slf4j
@Service
public class DataApiMarketApplicationService {

    @Autowired
    private DataApiService dataApiService;

    @Autowired
    private DirectoryService directoryService;

    @Autowired
    private DataApiAuthService dataApiAuthService;

    public List<DirectoryResponse> getDataApiGroupList() {
        Long projectId = ServletUtils.getProjectId();
        List<DirectoryDomain> dirList =
            directoryService.getDirList(projectId, DirectoryMenuEnum.API, null);

        return ConvertUtil.copyProperties(dirList, DirectoryResponse.class);
    }

    public PageResult<DataApiBaseResponse> getMarketApiList(String groupId, String apiName, Integer pageNum, Integer pageSize) {
        Long projectId = ServletUtils.getProjectId();
        List<Long> groupIds = Lists.newArrayList();

        String userId = UserContext.getUserId();
        if (StringUtils.isNotBlank(groupId)) {
            String[] split = groupId.split(",");
            groupIds = Arrays.stream(split).map(Long::valueOf).collect(Collectors.toList());
        }
        IPage<DataApiBaseDomain> r1 =
            dataApiService.getMarketApiList(projectId, groupIds, apiName, pageNum, pageSize, userId);

        return PageResult.copyPropertiesAndConvert(r1, DataApiBaseResponse.class);
    }

    public boolean applyApiById(Long apiId) {
        UserDomain userInfo = UserContext.getUserInfo();
        Long projectId = ServletUtils.getProjectId();
        return dataApiAuthService.applyApiById(userInfo.getId(), apiId, projectId, userInfo.getUserName());
    }

    public boolean applyApiByIds(String ids) {
        UserDomain userInfo = UserContext.getUserInfo();
        Long projectId = ServletUtils.getProjectId();
        if (StringUtils.isNotBlank(ids)) {
            String[] split = ids.split(",");
            List<Long> apiList = Arrays.stream(split).map(Long::valueOf)
                .collect(Collectors.toList());
            return dataApiAuthService.applyApiByIds(userInfo.getId(), apiList, projectId, userInfo.getUserName());
        }
        return false;
    }

    public DataApiResponse getDataApiDetailById(Long id) {
        DataApiDomain dataApiDomain = dataApiService.getDataApiDetailById(id);
        DataApiRegisterDomain apiRegisterDomain = dataApiDomain.getApiRegisterDomain();
        List<DataApiTaskParamDomain> apiParamDomainList = dataApiDomain.getApiParamEntityList();

        DataApiResponse dataApiResponse =
            ConvertUtil.copyProperties(dataApiDomain, DataApiResponse.class);

        dataApiResponse.setDataApiRegisterDomain(apiRegisterDomain);

        if (apiParamDomainList != null) {
            List<DataApiResponse.DataApiParamResponse> dataApiParamResponses =
                ConvertUtil.copyProperties(apiParamDomainList, DataApiResponse.DataApiParamResponse.class);
            Map<Integer, List<DataApiResponse.DataApiParamResponse>> collect =
                dataApiParamResponses.stream()
                    .collect(Collectors.groupingBy(DataApiResponse.DataApiParamResponse::getParamType));
            List<DataApiResponse.DataApiParamResponse> dataApiParamResponses1 = collect.get(0);
            List<DataApiResponse.DataApiParamResponse> dataApiParamResponses2 = collect.get(1);
            dataApiResponse.setOutputParamResponses(
                dataApiParamResponses2 == null ? new ArrayList<>() : dataApiParamResponses2);
            dataApiResponse.setInputParamResponses(
                dataApiParamResponses1 == null ? new ArrayList<>() : dataApiParamResponses1);
        }
        return dataApiResponse;
    }

    public Long testApi(Long apiId, HttpServletRequest request) {
        Long projectId = ServletUtils.getProjectId();
        return dataApiService.testApi(apiId, request, projectId);
    }

    public DataApiLogResponse getRequestLog(Long logId, Integer offset) {
        DataApiLogDomain requestLog = dataApiService.getRequestTestLog(logId, offset);
        return ConvertUtil.copyProperties(requestLog, DataApiLogResponse.class);
    }

    public void exportApi(String apiIds, HttpServletResponse response) {
        String userId = UserContext.getUserId();
        Long projectId = ServletUtils.getProjectId();

        if (StringUtils.isBlank(apiIds)) {
            throw new BusinessException("apiIds参数为空");
        }

        List<Long> ids =
            Lists.newArrayList(apiIds.split(",")).stream()
                .map(Long::valueOf)
                .collect(Collectors.toList());
        dataApiService.exportApi(ids, userId, projectId, response);
    }
}
